<template>
  <el-row @update:modelValue="updateModelValue" v-loading="fullPageLoading"
          element-loading-text="正在处理请求，请稍后...">
    <el-alert title="注意！生源地是你高考时户籍所在地，这个很重要，请确认清楚！" type="warning"
              :closable="false" show-icon/>
    <el-alert v-if="!stduentIsCheck" title="你还没有确认过生源地，请在下方输入你的生源地" type="warning"
              :closable="false" show-icon style="margin-top: 10px;"/>
    <el-divider border-style="dashed"/>
    <el-form v-if="!stduentIsCheck" ref="formRef" :model="form" label-width="auto"
             style="max-width: 600px;width: 500px;"
             :rules="rules">
      <el-form-item label="生源所在地" prop="studentSource">
        <el-cascader v-model="form.studentSource" :props="studentSourceOption" style="width: 100%;"/>
      </el-form-item>
      <el-form-item label=" ">
        <el-button type="primary" :loading="loading" @click="save">
          保存
        </el-button>
      </el-form-item>
    </el-form>
    <el-alert v-if="stduentIsCheck" type="success" :closable="false">
      <slot name="title">你已确认过你的生源地，你当前选定的生源地为：
        <el-text class="mx-1" type="success" tag="b">{{ studentSourceFullName }}</el-text>
      </slot>
    </el-alert>

    <div v-if="stduentIsCheck" style="text-align: center;padding-top: 30px;width: 100%;">
      <el-button type="danger" :loading="loading" @click="editSource">
        有点问题，我要修改
      </el-button>
      <el-button type="primary" :loading="loading" @click="goNext">
        我已经确认，下一步
      </el-button>
    </div>
    <EditSourceDialog v-if="editSourceDialogShow" v-model="editSourceDialogShow" @done="doneEditSource">
    </EditSourceDialog>
  </el-row>

</template>


<script setup>
import {reactive, ref} from 'vue';
import {getSource, submitSource} from '@/api/student';
import {selectByPlaceLevel} from '@/api/system/place'
import {EleMessage} from "ele-admin-plus";
import EditSourceDialog from './edit-source-dialog.vue';

const emit = defineEmits(['done', 'update:modelValue']);


const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Number,
});


/** 提交状态 */
const loading = ref(false);

/** 表单实例 */
const formRef = ref(null);

/**
 * 全屏遮罩层
 * @type {Ref<UnwrapRef<boolean>>}
 */
const fullPageLoading = ref(true);

/** 表单实例 */
const form = ref({
  studentSource: null,
});


/** 表单验证规则 */
const rules = reactive({
  studentSource: [
    {required: true, message: '请选择你的生源地', trigger: 'blur'},
  ],
});

/** 保存编辑 */
const save = () => {
  formRef.value?.validate?.((valid) => {
    if (!valid) {
      EleMessage.error('请选择你的生源地！');
      //错误提示
      return;
    }
    loading.value = true;
    console.log(form.value.studentSource);
    let place = form.value.studentSource.join(',');
    submitSource(place).then(res => {
      loading.value = false;
      //提交成功
      console.log(res.data);
      stduentIsCheck.value = true;
      studentSourceFullName.value = place.replace(',', '');
      //标识一下当前的生源地

    }).catch((e) => {
      console.log(res.data);
      EleMessage.error(e.message);
    });
  });

};

let id = 0;
const studentSourceOption = ref({
  lazy: true,
  lazyLoad(node, resolve) {
    console.log(node);
    let params = {};
    const {level} = node;
    let nodes = [];
    switch (level) {
      case 0:
        params = {
          name: node.value,
          level: node.level,
        };
        selectByPlaceLevel(params).then(response => {
          console.log(response.data);
          if (response.data) {
            nodes = response.data.map(item => ({
              value: item.value,
              label: item.label,
              leaf: item.leaf
            }));
          }
          resolve(nodes);
        });
        break;
      case 1:
        params = {
          name: node.value,
          level: node.level,
        };
        selectByPlaceLevel(params).then(response => {
          // console.log(response.data);
          if (response.data) {
            nodes = response.data.map(item => ({
              value: item.value,
              label: item.label,
              leaf: item.leaf
            }));
          }
          resolve(nodes);
        });
        break;
      case 2:
        params = {
          name: node.pathValues.join(','),
          level: node.level,
        };
        selectByPlaceLevel(params).then(response => {
          console.log(response.data);
          if (response.data) {
            nodes = response.data.map(item => ({
              value: item.value,
              label: item.label,
              leaf: item.leaf
            }));
          }
          resolve(nodes);
        });
        break;
    }
  }
});


//获取当前学生的生源地
//如果当前学生的生源为“未知生源地”，那么标注当前学生的生源地为没有确认过

//如果已经确认过，那么判断下是否可以修改


//标识当前学生是否已经确认过生源地
const stduentIsCheck = ref(false);

const studentSourceName = ref('');
const studentSourceFullName = ref('');

//标识当前学生的生源地是否还存在数据库中
const sourceIsExist = ref(false);

const getStduentSource = () => {
  //获取学生生源地
  getSource().then(response => {
    if (response.data) {
      // console.log(response.data)

      if (response.data.sourceName == '未知生源地' || !response.data.sourceFullName) {
        //当前学生没有确认过生源地
        stduentIsCheck.value = false;
      } else {
        stduentIsCheck.value = true;
        //当前学生已经确认过生源地
        studentSourceName.value = response.data.sourceName;
        studentSourceFullName.value = response.data.sourceName;
      }
    } else {
      stduentIsCheck.value = false;
    }
    fullPageLoading.value = false;
  });
}


const index = ref(props.modelValue);

const goNext = () => {

  console.log("index", index.value);

  //跳转到下一步
  index.value = index.value + 1;
  updateModelValue(index.value);//index的值
  // emit("done", index.value);
}


/** 更新modelValue */
const updateModelValue = (value) => {
  emit('update:modelValue', value);
};

/** 编辑生源所在地对话框 */
const editSourceDialogShow = ref(false);

const editSource = () => {
  //编辑生源地
  editSourceDialogShow.value = true;
  // console.log("editSourceDialogShow", editSourceDialogShow.value);
  //弹框修改
}

const doneEditSource = (place) => {
  studentSourceFullName.value = place;
}


//获取学生生源地
getStduentSource();


</script>
